<?php
// 应用公共文件


//请求url获取结果
function curl_url($url, $method = 'get', $data = null, $https = true)
{
    if ($method == 'get' && $data) {
        $url = $url . '?' . http_build_query($data);
    }
    //1.初识化curl
    $ch = curl_init($url);
    //2.根据实际请求需求进行参数封装
    //返回数据不直接输出
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    //如果是https请求
    if ($https === true) {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    }
    //如果是post请求
    if ($method === 'post') {
        //开启发送post请求选项
        curl_setopt($ch, CURLOPT_POST, true);
        //发送post的数据
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }
    //3.发送请求
    $result = curl_exec($ch);
    //4.返回返回值，关闭连接
    curl_close($ch);
    return $result;
}

function success($msg = 'ok', $data = [], $meta = [])
{
    return json([
        'code' => 0,
        'msg'  => $msg,
        'data' => $data,
        'meta' => $meta
    ]);
}

function error($msg, $data = [], $meta = [])
{
    return json([
        'code' => 500,
        'msg'  => $msg,
        'data' => $data,
        'meta' => $meta
    ]);
}

function purview_tree($arrData, $selectId = '')
{
    if (empty($arrData)) {
        return '';
    }
    $str = '';
    foreach ($arrData as $arrVal) {
        echo $arrVal['name'] . PHP_EOL;
        $selectStr = '';
        if ($selectId && $arrVal['id'] == $selectId) {
            $selectStr = 'selected';
        }
        $spaceStr = str_repeat('&nbsp&nbsp&nbsp&nbsp', $arrVal['level']) . '--';
        $str .= "<option value='{$arrVal['id']}' {$selectStr}>{$spaceStr} {$arrVal['name']}</option>";
        if (!empty($arrVal['sub'])) {
            $str .= purview_tree($arrVal['sub']);
        }
    }
    return $str;
}

function purview_tree_no_sub($arrData, $pid = 0, $level = 1, $idName = 'id', $pidName = 'pid')
{
    $arrTree = [];
    foreach ($arrData as $k => $v) {
        if ($v[$pidName] == $pid) {
            $v['level'] = $level;
            $arrTree[$v[$idName]] = $v;
            $arrTree = $arrTree + purview_tree_no_sub($arrData, $v[$idName], $level + 1, $idName, $pidName);
        }
    }
    return $arrTree;
}

function upload_file($file, $key = 'file')
{
    if (!isset($file[$key]) || $file[$key]["error"] != UPLOAD_ERR_OK) {
        return '';
    }
    list($name, $suffix) = explode('.', $file[$key]["name"]);
    $img = './public/static/files/' . date('Ymd-') . time() . $suffix;
    move_uploaded_file($file[$key]["tmp_name"], $img);
    return $img;
}

function yes_or_no($val)
{
    return $val == 1 ? '是' : '否';
}

